/*
 * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
 * For example, given array S = {-1 2 1 -4}, and target = 1.
 * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 */
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int size = num.size();
        if (size < 3) {
            return 0;
        }
        std::sort(num.begin(), num.end());
        int diff = 1000000;
        for (int i = 0; i < size-2; i++) {
            if (i > 0 && num[i] == num[i-1]) { /* remove dups */
                continue;
            }
            int j = i + 1;
            int k = size - 1;
            while (j < k) {
                int sum = num[j] + num[k];
                if (k < size-1 && num[k] == num[k+1]) { /* remove dups */
                    k--;
                } else if (sum + num[i] == target) {
                    return target;
                } else {
                    int d = sum+num[i] - target;
                    if (abs(diff) > abs(d)) {
                        diff = d;
                    }
                    if (sum+num[i] < target) {
                       j++;
                    } else {
                       k--;
                    }
                }
            }
        }
        return target+diff;
    }
};

int main() {
    return 0;
}
